package org.fdy.common.core.units;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.fdy.common.core.constant.Constants;
import org.fdy.common.core.constant.RedisConstant;
import org.fdy.common.core.model.auth.SaUser;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>说明：用户信息 </P>
 *
 * @author: fangdayang
 * @create: 2023-10-21 17:38
 **/
@Slf4j
public class LoginUtils {

    /**
     * 用户登录 并设置用户信息
     *
     * @param saUser 登录用户信息
     */
    public static void login(SaUser saUser) {
        StpUtil.login(saUser.getUserId());
        setSaUser(saUser);
    }

    /**
     * 设置用户信息
     * @param saUser
     */
    private static void setSaUser(SaUser saUser) {
        SaSession tokenSession = StpUtil.getTokenSession();
        tokenSession.set(Constants.LOGIN_USER_KEY, saUser);

    }

    /**
     * 获取用户
     **/
    public static SaUser getLoginUser() {
        SaSession tokenSession = StpUtil.getTokenSession();
        if (Objects.isNull(tokenSession)){
            return null;
        }
        return (SaUser) tokenSession.get(Constants.LOGIN_USER_KEY);
    }

    /**
     * 获取用户id
     */
    public static Long getUserId() {
        SaUser saUser = getLoginUser();
        if (Objects.isNull(saUser)) {
            String loginId = StpUtil.getLoginIdAsString();
            return Long.parseLong(loginId);
        }
        return saUser.getUserId();
    }
}
